# Makefile for RISC-V Test Program

# Toolchain configuration
CROSS_COMPILE = riscv64-unknown-elf-
CC = $(CROSS_COMPILE)gcc
LD = $(CROSS_COMPILE)ld
OBJCOPY = $(CROSS_COMPILE)objcopy
OBJDUMP = $(CROSS_COMPILE)objdump

# Compiler flags
CFLAGS = -march=rv32imc -mabi=ilp32 -Os -Wall -Wextra -ffreestanding -nostdlib -nostartfiles
LDFLAGS = -T linker.ld

# Source files
SRCS = hello.c crt0.S

# Object files
OBJS = $(SRCS:.c=.o)
OBJS := $(OBJS:.S=.o)

# Targets
all: hello.bin

# Compile C files
%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

# Compile assembly files
%.o: %.S
	$(CC) $(CFLAGS) -c $< -o $@

# Link
hello.elf: $(OBJS)
	$(LD) $(LDFLAGS) -o $@ $^

# Generate binary
hello.bin: hello.elf
	$(OBJCOPY) -O binary $< $@
	$(OBJDUMP) -d $< > hello.dis

# Clean
clean:
	rm -f *.o *.elf *.bin *.dis

# Run in QEMU
run:
	qemu-system-riscv32 -machine virt -cpu rv32imc -m 128M -nographic \
	-kernel hello.elf

.PHONY: all clean run
